//
//  Fields.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/23/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import Foundation

struct OptionSection {
    var name: String
    var single_fields: [SingleField] = []
    var choice_fields: [ChoiceField] = []
    var multiple_fields: [MultipleField]

    init (_ data: NSArray, name: String) {
        self.name = name

        let sfData = (data[0] as! NSArray)[1] as! [[String]]

        self.single_fields = sfData.map({ (arr) -> SingleField in
            return SingleField(key: arr[0], value: arr[1])
        })
        
        let chData = (data[1] as! NSArray)[1] as! NSArray
        self.choice_fields = chData.map({ (x) -> ChoiceField in
            return ChoiceField((x as! NSArray)[1] as! NSDictionary, key: (x as! NSArray)[0] as! String)
        })


        let mfData = (data[2] as! NSArray)[1] as! NSArray
        self.multiple_fields = mfData.map({ (x) -> MultipleField in
            return MultipleField((x as! NSArray)[1] as! NSDictionary, key: (x as! NSArray)[0] as! String)
        })
    }
}

struct SingleField {
    var key: String
    var name: String
    var isSelected: Bool = false

    init (key: String, value: String) {
        self.key = key
        self.name = value
    }
}


struct MultipleField {

    var key: String
    var name: String
    var fields: [MultipleItem] = []
    var isExpanded: Bool = false
    var selectedItems: [Int] = []

    init (_ data: NSDictionary, key: String) {
        self.key = key
        self.name = data["name_ru"] as! String
        let temp = data["fields"] as! NSDictionary
        self.fields = (temp.allKeys as! [String]).map({ (x) -> MultipleItem in
            return MultipleItem(id: Int(x)!, name: temp[x] as! String)
        })
    }
}

struct ChoiceField {
    var key: String
    var name: String
    var fields: [ChoiceItem] = []
    var selectedId: Int? = nil
    var isExpanded: Bool = false

    init (_ data: NSDictionary, key: String) {
        self.key = key
        self.name = data["name_ru"] as! String

        let temp = data["fields"] as! [NSArray]
        self.fields = temp.map({ (arr) -> ChoiceItem in
            return ChoiceItem(arr)
        })
    }
}

struct MultipleItem {
    var id: Int = 0
    var name: String = ""

    init (id: Int, name: String) {
        self.id = id
        self.name = name
    }
}

struct ChoiceItem {
    var id: Int = 0
    var name: String = ""

    init (_ data: NSArray) {
        self.id = data[0] as! Int
        self.name = data[1] as! String
    }
}
